import { createPersistedStore } from '../services/store.service';
import { ChatService } from '../services/chat.service';

export interface Message {
  id: string;
  text: string;
  isBot: boolean;
  timestamp: number;
}

interface ChatState {
  histories: Record<string, Message[]>;
  currentService: string;
  isLoading: boolean;
  error: string | null;
  
  // Actions
  setCurrentService: (serviceId: string) => void;
  addMessage: (text: string, isBot: boolean) => void;
  sendMessage: (text: string, systemPrompt: string) => Promise<void>;
  clearHistory: (serviceId: string) => void;
}

export const useChatStore = createPersistedStore<ChatState>(
  {
    name: 'chat-store',
    initialState: {
      histories: {},
      currentService: 'default',
      isLoading: false,
      error: null,
    },
    onRehydrate: (state) => {
      console.log('Chat store rehydrated:', state);
    },
  },
  (set, get) => ({
    setCurrentService: (serviceId) => set({ currentService: serviceId }),

    addMessage: (text, isBot) => {
      const { currentService, histories } = get();
      const newMessage = {
        id: Date.now().toString(),
        text,
        isBot,
        timestamp: Date.now(),
      };

      set({
        histories: {
          ...histories,
          [currentService]: [
            ...(histories[currentService] || []),
            newMessage,
          ],
        },
      });
    },

    sendMessage: async (text, systemPrompt) => {
      const { addMessage } = get();
      
      set({ isLoading: true, error: null });
      addMessage(text, false);

      try {
        const reply = await ChatService.sendMessage(text, systemPrompt);
        addMessage(reply, true);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '发生未知错误';
        set({ error: errorMessage });
        addMessage('抱歉，发生了一些错误。请稍后再试。', true);
      } finally {
        set({ isLoading: false });
      }
    },

    clearHistory: (serviceId) => {
      const { histories } = get();
      set({
        histories: {
          ...histories,
          [serviceId]: [],
        },
      });
    },
  })
);